package com.atguigu.guli.service.sms.controller.api;

import com.atguigu.guli.common.util.FormUtils;
import com.atguigu.guli.common.util.RandomUtils;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.sms.service.SmsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author lsj
 * @create 2021-07-14 11:20
 */
@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信，将验证码存入redis
     * @param mobile
     * @return
     */
    @GetMapping("send/{mobile}")
    public R send(@PathVariable String mobile){

        if(StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)){
            return R.setResult(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }

        String checkCode = RandomUtils.getFourBitRandom();
        //发送短信
        smsService.sendSms(mobile, checkCode);

        //将验证码存入redis
        redisTemplate.opsForValue().set("checkCode:" + mobile, checkCode, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}